import com.seeyon.cap4.form.bean.FormDataMasterBean
import com.seeyon.cap4.form.bean.FormDataSubBean
import com.seeyon.cap4.form.service.CAP4FormManager
import com.seeyon.ctp.common.AppContext
import com.seeyon.ctp.common.ctpenumnew.manager.EnumManager
import com.seeyon.ctp.common.po.ctpenumnew.CtpEnumItem
import com.seeyon.ctp.organization.bo.V3xOrgMember
import com.seeyon.ctp.organization.manager.OrgManager
import com.seeyon.dee.codelib.TcDateKit
import com.seeyon.dee.codelib.TcFormCap4Kit

import java.text.SimpleDateFormat
import java.util.stream.Collectors


//出差申请商旅订票
def masterId = getParaByName(document,"masterId");
CAP4FormManager cap4FormManager = (CAP4FormManager)AppContext.getBean("cap4FormManager");
EnumManager enumManager = AppContext.getBean("enumManagerNew");
OrgManager orgManager = (OrgManager) AppContext.getBean("orgManager");


FormDataMasterBean formDataMasterBean = cap4FormManager.getSessioMasterDataBean(masterId);
if(formDataMasterBean == null){
    printlnLog("出差申请商旅订票获取缓存formDataMasterBean为null，masterId："+masterId);
}

boolean isDefault = false;
int index = 1;
//明细表中的值
List<HashMap<String,Object>> itemList = new ArrayList<HashMap<String, Object>>();
List<FormDataSubBean> displayList = TcFormCap4Kit.getSubBeansByDisplay(formDataMasterBean, "出差明细");
for (FormDataSubBean display :displayList){
    HashMap<String,Object> itemMap = new HashMap<String, Object>()
    //预计开始时间小时
    def person = TcFormCap4Kit.getSubFieldValue(display, "出差人");
    itemMap.put("person",person);


    //预计开始时间小时
    def startHour = TcFormCap4Kit.getSubFieldValue(display, "预计开始时间小时");
    if(startHour != null){
        CtpEnumItem startHourEnum = enumManager.getCtpEnumItem((Long)startHour);
        if(startHourEnum != null){
            itemMap.put("startHour",startHourEnum.getShowvalue());
        }
    }else{
        isDefault = true;
        break;
    }

    //预计开始时间小时
    def startMinute = TcFormCap4Kit.getSubFieldValue(display, "预计开始时间分钟");
    if(startMinute != null){
        CtpEnumItem startMinuteEnum = enumManager.getCtpEnumItem((Long)startMinute);
        if(startMinuteEnum != null){
            itemMap.put("startMinute",startMinuteEnum.getShowvalue());
        }
    }else{
        isDefault = true;
        break;
    }

    //预计结束时间小时
    def overHour = TcFormCap4Kit.getSubFieldValue(display, "预计结束时间小时");
    if(overHour != null){
        CtpEnumItem overHourEnum = enumManager.getCtpEnumItem((Long)overHour);
        if(overHourEnum != null){
            itemMap.put("overHour",overHourEnum.getShowvalue());
        }
    }else{
        isDefault = true;
        break;
    }
    //预计结束时间分钟
    def overMinute = TcFormCap4Kit.getSubFieldValue(display, "预计结束时间分钟");
    if(overMinute != null){
        CtpEnumItem overMinuteEnum = enumManager.getCtpEnumItem((Long)overMinute);
        if(overMinuteEnum != null){
            itemMap.put("overMinute",overMinuteEnum.getShowvalue());
        }
    }else{
        isDefault = true;
        break;
    }


    String startDate = TcDateKit.getSp(TcFormCap4Kit.getSubFieldValue(display, "预计开始时间"))
    //差旅开始时间
    itemMap.put("startDate",startDate);
    //差旅结束时间
    String endDate = TcDateKit.getSp(TcFormCap4Kit.getSubFieldValue(display, "预计结束时间"))
    itemMap.put("endDate",endDate);
    if(startDate.equals("") || endDate.equals("")){
        isDefault = true;
        break;
    }
    itemList.add(itemMap);
    index++;
}
if(!isDefault){
    boolean hasOverlap = false;
    String errorMsg = "";
    //判断开始时间和结束时间是否存在重叠
    SimpleDateFormat sp1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Map<Object, List<HashMap<String, Object>>> collect = itemList.stream().collect(Collectors.groupingBy({ it -> it["person"] }, Collectors.toList()))
    collect.keySet().forEach({
        //获取人员信息
        V3xOrgMember v3xOrgMember1 = orgManager.getMemberById(Long.parseLong(it.toString()))
        List<HashMap<String, Object>> dataList = collect.get(it);
        // 对 dataList 按开始时间进行排序
        dataList.sort(Comparator.comparing({ item -> sp1.parse(item["startDate"].toString()+" "+item["startHour"].toString()+":"+item["startMinute"].toString()+":00")}));
        // 遍历 itemList 检查是否存在重叠
        for (int i = 0; i < dataList.size() - 1; i++) {
            HashMap<String, Object> current = dataList.get(i);
            HashMap<String, Object> next = dataList.get(i + 1);

            Date currentEndDate = sp1.parse(current.get("endDate").toString()+" "+current.get("overHour").toString()+":"+current.get("overMinute").toString()+":00");
            Date nextStartDate = sp1.parse(next.get("startDate").toString()+" "+next.get("startHour").toString()+":"+next.get("startMinute").toString()+":00");

            // 检查当前项的结束时间是否晚于或等于下一项的开始时间
//            currentEndDate.after(nextStartDate) || currentEndDate.equals(nextStartDate)
            if (currentEndDate.after(nextStartDate)) {
                // 根据需要处理重叠情况
                SimpleDateFormat sp2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                hasOverlap=true;
                errorMsg += "发现【"+v3xOrgMember1.getName()+"】的出差明细行重叠时间段: 当前项结束时间 " + sp2.format(currentEndDate) + " 与下一项开始时间 " + sp2.format(nextStartDate) + " 重叠；";
            }
        }
    })
    if(hasOverlap){
        setHighSetStr(document,'F','Y',errorMsg,'');
    }
}else{
    setHighSetStr(document,'F','Y',"明细表第"+index+"行，开始时间或结束时间为空！",'');
}